package com.iflytek.service;
import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl implements MailService {

	private final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private JavaMailSender mailSender;

	@Value("${spring.mail.username}")   //从配置文件读取发件人信息
	private String from;

	@Override
	public void sendSimpleMail(String to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);   		//发件人名称
		message.setTo(to);      		//收件人邮件地址，可以是多个，使用逗号分割
		message.setSubject(subject);    //邮件的主题
		message.setText(content);		//邮件的正文内容

		logger.debug("开始发送文本邮件。");
		try {
			mailSender.send(message);
			logger.info("文本邮件已经发送。");
		} catch (Exception e) {
			logger.error("发送文本邮件时发生异常！", e);
		}
	}

	@Override
	public void sendHtmlMail(String to, String subject, String content, File... attachments) {
		MimeMessage message = mailSender.createMimeMessage();

		logger.debug("开始发送HTML邮件。");
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content, true);
			
			//添加附件
			if(attachments != null && attachments.length > 0) {
				for(File f : attachments) {
					helper.addAttachment(f.getName(), f);  
				}
			}

			mailSender.send(message);
			logger.info("HTML邮件发送成功");
		} catch (MessagingException e) {
			logger.error("发送HTML邮件时发生异常！", e);
		}
	}
}